"use server";

import * as z from "zod";
import bcrypt from "bcryptjs";

import { RegisterSchema } from "@/schemas";
console.log("backserverurl environment", process.env.BACK_SERVER_URL);
const backServerUrl = process.env.BACK_SERVER_URL;
export const register = async (values: z.infer<typeof RegisterSchema>) => {
  const validatedFields = RegisterSchema.safeParse(values);
  if (!validatedFields.success) {
    return { error: "Invalid fields!" };
  }

  const { email, name, password } = validatedFields.data;
  const hashedPassword = await bcrypt.hash(password, 10);
  //  const verificationToken = await generateVerificationToken(email);
  const data = { name: name, email: email, password: hashedPassword };
  console.log(`create user ${backServerUrl}/api/user`);
  const resp = await fetch(`/api/user`, {
    method: "POST",
    body: JSON.stringify(data),
  });
  if (resp.ok) {
    return { error: "", success: "successfull" };
  } else {
    console.log(backServerUrl);
    console.log(await resp.json());
    return { error: "create acount failed", success: "" };
  }
};
